# coding:utf-8
from django.core.paginator import InvalidPage
from rest_framework import pagination, viewsets
from rest_framework.decorators import action
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.permissions import AllowAny

from app.autojob.columns import init_task_columns, install_task_columns
from app.autojob.data_opt import ticket_detail_tree_data, submit_task_data, get_task_log, get_init_script_log, retry_task
from app.autojob.filters import InitTaskListFilter, OSInstallTaskListFilter
from app.autojob.models import InitTaskList, OSInstallTaskList
from common.libs.common import jsonify
from app.autojob.serializers import InitTaskListSerializer, OSInstallTaskListSerializer
from django_filters.rest_framework import DjangoFilterBackend


class AllPagination(pagination.PageNumberPagination):  # 继承DRF自带的PageNumberPagination类，拿到类里通用的分页功能

    page_size = 10  # 每页总数
    page_size_query_param = 'page_size'  # 动态指定页数
    max_page_size = 1000  # 最大1000条

    def paginate_queryset(self, queryset, request, view=None):  # 在取到真实数据前，会调用这个方法，会返回当前页展示的对象列表，如果返回None表示本次不分页
        """
        Paginate a queryset if required, either returning a
        page object, or `None` if pagination is not configured for this view.
        """

        page_size = self.get_page_size(request)  # 解析最终每页条数
        if not page_size:
            return None  # 如果解析失败，原样返回queryset

        paginator = self.django_paginator_class(queryset,page_size)  # 用django自带的paginator(queryset, page_size)生成一个分页器对象
        page_number = self.get_page_number(request, paginator)  # 从url中拿页码

        try:
            self.page = paginator.page(page_number)
        except InvalidPage:
            self.page = paginator.page(1)  # 做异常处理，如果页码超出范围或错误，自动退回到1，正常则跳转页码

        if paginator.num_pages > 1 and self.template is not None:
            # The browsable API should display pagination controls.
            self.display_page_controls = True  # 当总页数大于1且当前是可浏览的api或html页面时，才在页面上显示 上一页下一页按钮

        self.request = request  # 请求对象放到实例中，后续drf响应会用到
        return list(self.page)  # 返回当前页对象列表，drf会转换成json给前端


class InitTaskListViewSet(viewsets.ModelViewSet):
    """物理机"""
    permission_classes = [AllowAny]
    queryset = InitTaskList.objects.all()
    serializer_class = InitTaskListSerializer

    pagination_class = AllPagination

    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_class = InitTaskListFilter
    search_fields = ['systemSN', 'ticketSn', 'businessIp', 'idc', 'status', 'is_deleted']

    def list(self, request, *args, **kwargs):
        total = 0
        data = []
        tab = request.query_params.get('tab')
        columns, forms = init_task_columns(tab)
        response = super().list(request, *args, **kwargs)
        if 'results' in response.data:
            data = response.data['results']
            total = response.data['count']
        return jsonify(code=200, success=True, total=total, data=data, columns=columns, forms=forms)

    @action(detail=False, methods=['get'])
    def get_ticket_detail(self, request, *args, **kwargs):
        param = request.query_params
        data = ticket_detail_tree_data(param)
        return jsonify(code=200, success=True, data=data, msg='success')

    @action(detail=False, methods=['post'])
    def submit_ticket_detail(self, request, *args, **kwargs):
        """"""
        data = request.data
        res, msg = submit_task_data(request, data)
        return jsonify(code=200, success=res, data=[], msg=msg)

    @action(detail=False, methods=['get'])
    def init_task_log(self, request, *args, **kwargs):
        param = request.query_params
        res, msg, data = get_task_log(param)
        return jsonify(code=200, success=res, data=data, msg=msg)

    @action(detail=False, methods=['get'])
    def look_init_script_log(self, request, *args, **kwargs):
        param = request.query_params
        res, msg, data = get_init_script_log(param)
        return jsonify(code=200, success=res, data=data, msg=msg)

    @action(detail=False, methods=['post'])
    def retry_init_task(self, request, *args, **kwargs):
        """"""
        data = request.data
        res, msg = retry_task(request, data)
        return jsonify(code=200, success=res, data=[], msg=msg)


class OSInstallTaskListViewSet(viewsets.ModelViewSet):
    """物理机"""
    permission_classes = [AllowAny]
    queryset = OSInstallTaskList.objects.all()
    serializer_class = OSInstallTaskListSerializer

    pagination_class = AllPagination

    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_class = OSInstallTaskListFilter
    search_fields = ['systemSN', 'ticketSn', 'businessIp', 'idc', 'status', 'is_deleted', 'netEnv']

    def list(self, request, *args, **kwargs):
        total = 0
        data = []
        tab = request.query_params.get('tab')
        columns, forms = install_task_columns(tab)
        response = super().list(request, *args, **kwargs)
        if 'results' in response.data:
            data = response.data['results']
            total = response.data['count']
        return jsonify(code=200, success=True, total=total, data=data, columns=columns, forms=forms)
# Create your views here.
